package ddx;

import java.awt.Robot;
import java.text.SimpleDateFormat;
import java.util.Date;

import com.sun.jna.platform.win32.Kernel32;
import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef.HMODULE;
import com.sun.jna.platform.win32.WinDef.LRESULT;
import com.sun.jna.platform.win32.WinDef.WPARAM;
import com.sun.jna.platform.win32.WinUser.MSLLHOOKSTRUCT;
import com.sun.jna.platform.win32.WinUser;

public class MouseHook implements Runnable{
	Robot rb;
	private WinUser.HHOOK hhk;
	
	int WM_LBUTTONDOWN = 0x0201;
    int WM_LBUTTONUP = 0x0202;
    int WM_MOUSEMOVE = 0x0200;
    int WM_MOUSEWHEEL = 0x020A;
    int WM_RBUTTONDOWN = 0x0204;
    int WM_RBUTTONUP = 0x0205;
    int WM_MOUSEWHEELUP = 0x0208;
    int WM_MOUSEWHEELDOWN = 0x0207;
    
	//钩子回调函数
	private WinUser.LowLevelMouseProc keyboardProc = new WinUser.LowLevelMouseProc() {
		 
  
		@Override
		public LRESULT callback(int nCode, WPARAM wParam, MSLLHOOKSTRUCT event) { 
			// 输出按键值和按键时间
			if (nCode >= 0) {
				String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
				
				//System.out.println(nCode); System.out.println(wParam);
				//WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_MOUSEWHEEL, WM_RBUTTONDOWN, WM_RBUTTONUP .
				switch(wParam.intValue()){
				case 0x0201:
					System.out.println(event.pt.x+":"+event.pt.y);
					System.out.println("l_down");
					break;
				case 0x0202:
					System.out.println(event.pt.x+":"+event.pt.y);
					System.out.println("l_UP");	
					break;
				case 0x0200:
					//System.out.println("MOVE");
					break;
				case 0x020A:
					//mouseData的正负值 确定滑轮是上还是下
					//System.out.println("WHEEL"+event.mouseData);	
					break;
				case 0x0204:
					//System.out.println("R_down");	
					break;
				case 0x0205:
					//System.out.println("R_UP");	
					break;
				case 0x0207:
					//System.out.println("WHEEL_DWON");	
					break;
				case 0x0208:
					//System.out.println("WHEEL_UP");	
					break;
				default:
					//System.out.println("米有");	
					
					
				}
				 
			  
			}
			return User32.INSTANCE.CallNextHookEx(hhk, nCode, wParam, null);
		}
	};//MyBlog @See http://blog.csdn.net/shenpibaipao
   
	public void run() {
		setHookOn();
	}
	// 安装钩子
	public void setHookOn(){
		System.out.println("Mouse Hook On!");
 
		HMODULE hMod = Kernel32.INSTANCE.GetModuleHandle(null);
										//User32.WH_MOUSE_LL
		hhk = User32.INSTANCE.SetWindowsHookEx(User32.WH_MOUSE_LL, keyboardProc, hMod, 0);
 
		int result;
		WinUser.MSG msg = new WinUser.MSG();
		while ((result = User32.INSTANCE.GetMessage(msg, null, 0, 0)) != 0) {
			if (result == -1) {
				setHookOff();
				break;
			} else {
				User32.INSTANCE.TranslateMessage(msg);
				User32.INSTANCE.DispatchMessage(msg);
			}
		}
	}
	// 移除钩子并退出
	public void setHookOff(){
		System.out.println("Hook Off!");
		User32.INSTANCE.UnhookWindowsHookEx(hhk);
		System.exit(0);
	}
}
 
    
 
 